<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of jckWidgetFormLocalizeCity
 *
 * @author stephane
 */
class jckWidgetFormLocalizeCity extends sfWidgetFormInputText {
  public function __construct($options = array(), $attributes = array()) {
    parent::__construct($options, $attributes);
  }

  protected function configure($options = array(), $attributes = array()) {
    parent::configure($options, $attributes);
  }

  public function render($name, $value = null, $attributes = array(), $errors = array()) {
    return parent::render($name, $value, $attributes, $errors).'
      <script type="text/javascript">
      $(function(){
        var cache = {},
        lastXhr;
        $( "#'.$this->generateId($name).'" ).autocomplete({
          minLength: 2,
          source: function( request, response ) {
            console.debug(response);
            var address = request.address;
            if ( address in cache ) {
              response( cache[ address ] );
              return;
            }

            lastXhr = $.get( "'.url_for('jck_location_get_address', array('sf_format'=>'xml')).'", request, function( data, status, xhr ) {
              var output = new Array();
              var value = "";
              $(data).find("address").each(function(){
                console.info($(this).find("zipcode").text());
                console.info($(this).find("city").text());
                value = $(this).find("zipcode").text()+" " +$(this).find("city").text();
                output.push(value);
              });
              console.debug(cache);
              if ( xhr === lastXhr ) {
                response( output );
              }
            });
          }
        });
      });
      </script>';
  }

  public function getJavaScripts() {
    $js = parent::getJavaScripts();
    if( $jquery_core = sfConfig::get('app_jck_jquery_core') ){ $js[] = $jquery_core; }
    if( $jquery_ui = sfConfig::get('app_jck_jquery_ui') ){ $js[] = $jquery_ui; }
    $js[] = '/jckLocationPlugin/js/jckLocationCityAutoCompleter.js';
    return array_unique($js);

  }

  public function getStylesheets() {
    return array(sfConfig::get('app_jck_jquery_css')=>'screen');
  }
}
?>
